<template>
  <t-card :bordered="false" shadow>
    <t-space class="w-full" direction="vertical">
      <t-row>
        <t-col :span="12">
          <span
            class="text-6xl font-weight-light"
            v-text="cameraIpList.length"
          ></span>
          <span class="subheading text-base font-light me-1">台相机</span>
        </t-col>
      </t-row>

      <t-row class="w-full">
        <t-col :span="12">
          <t-textarea
            class="w-full"
            v-model="cameraIps"
            :autosize="{ minRows: 5, maxRows: 10 }"
            placeholder="相机地址（每个 IP 用逗号或换行分隔）"
            @change="handleInputBulkImport"
          />
        </t-col>
      </t-row>
      <div class="flex justify-end">
        <t-space>
          <t-button
            shape="rectangle"
            variant="dashed"
            :disabled="!cameraIpList.length"
            @click="handleImportResultsOpen"
            >查看相机地址</t-button
          >
          <t-button
            :disabled="!cameraIpList.length"
            :loading="loading"
            @click="handleInputSubmit"
            >应用</t-button
          >
        </t-space>
      </div>
    </t-space>
  </t-card>

  <t-dialog
    class="h-full"
    attach="#app"
    header="相机地址"
    placement="center"
    v-model:visible="viewOpen"
    :confirmBtn="null"
    cancel-btn="关闭"
    @close="handleImportResultsClose"
  >
    <t-base-table
      size="small"
      maxHeight="500"
      row-key="index"
      :data="data"
      :columns="columns"
    >
      <template #url="{ row }">
        <span class="text-base" v-if="!row.isUpdate">{{ row.url }}</span>
        <t-input
          class="w-full"
          v-else
          v-model:value="row.url"
          autofocus
          @blur="handleTableCellInputBlur"
        />
      </template>

      <template #operation="{ row }">
        <t-button
          shape="circle"
          theme="primary"
          @click="
            () => {
              row.isUpdate = !row.isUpdate;
            }
          "
        >
          <template #icon>
            <EditIcon v-if="!row.isUpdate" />
            <EditOffIcon v-else />
          </template>
        </t-button>
      </template>
    </t-base-table>
  </t-dialog>
</template>

<script setup>
import { ref } from "vue";
import { EditIcon, EditOffIcon } from "tdesign-icons-vue-next";
import { MessagePlugin } from "tdesign-vue-next";
import { addCameraList, listGetCamera } from "@/api/common";

// 获取相机列表
const fetchCameraList = async () => {
  const res = await listGetCamera();
  console.log("获取相机列表: ", res);
  const data = res?.data || [];
  cameraIpList.value = data.cameras.map((item) => item.ip);
  cameraIps.value = formatLinks(cameraIpList.value.join(","));
};

fetchCameraList();

const cameraIps = ref("");
const cameraIpList = ref("");
const handleInputBulkImport = (value) => {
  cameraIps.value = formatLinks(value);
  const urls = value.split(/[\s,，]+/).filter((url) => url.trim() !== "");
  cameraIpList.value = urls;
};

const loading = ref(false);
const handleInputSubmit = async () => {
  try {
    const cameras = cameraIpList.value.map((ip) => ({
      ip,
    }));
    const num = cameras.length;
    loading.value = true;
    const params = JSON.stringify({ cameras, num })
    await addCameraList(params);
    MessagePlugin.success("添加成功");
  } catch (error) {
    console.log("handleInputSubmit", error);
  } finally {
    loading.value = false;
  }
};

const viewOpen = ref(false);
const columns = ref([
  { colKey: "index", title: "#", width: "50" },
  { colKey: "url", title: "流地址" },
  { colKey: "operation", title: "操作", width: "70" },
]);
const data = ref([]);

const handleImportResultsOpen = () => {
  viewOpen.value = true;
  data.value = cameraIpList.value.map((url, index) => ({
    index: index + 1,
    url: url,
  }));
};

const handleTableCellInputBlur = () => {
  data.value.forEach((item) => (item.isUpdate = false));
};

const handleImportResultsClose = () => {
  viewOpen.value = false;
  const urls = data.value.map((item) => item.url);

  for (let i = 0; i < urls.length; i++) {
    if (urls[i] === "") {
      urls.splice(i, 1);
      i--;
    }
  }
  cameraIpList.value = urls;
  cameraIps.value = formatLinks(cameraIpList.value.join(","));
};

function formatLinks(inputText) {
  // 使用正则表达式将英文逗号和中文逗号分割，去掉每个链接前后的空格
  const links = inputText
    .split(/[\s,，]+/)
    .map((link) => link.trim())
    .filter((link) => link !== "");
  // 将每个链接连接成一个以换行符为分隔的字符串
  return links.join("\n");
}
</script>

<style scoped></style>
